package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-12
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        //判断用户名或密码都不为空
        if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NAME_PWD_REQUIRE);
        }
        //1.先根据用户名查询如果查询不到，返回一个错误提示
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(queryWrapper);
        if(one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NAME_ERROR);
        }
        //2.如果能查询到，再比较密码热狗密码不一致，返回一个错误提示
        String password_page = DigestUtils.md5Hex(dto.getPassword() + one.getSalt());
        String password_db = one.getPassword();
        if(!org.apache.commons.lang3.StringUtils.equals(password_page,password_db)){
            //热狗密码不一致，返回一个错误提示
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3.如果密码一直，返回结果，用户信息，jwt生成的字符串
        Map resultMap = new HashMap();
        one.setSalt("");
        one.setPassword("");
        one.setPhone("");
        one.setEmail("");
        resultMap.put("user",one);

        Map map = new HashMap();
        map.put("userId", one.getId());
        map.put("name", one.getName());
        String token = AppJwtUtil.getToken(map);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
